{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a9183228-0ba6-4af9-8430-649e28868253",
   "metadata": {
    "id": "JMXGlIvAwn30"
   },
   "source": [
    "# 聊天\n",
    "\n",
    "利用聊天格式与针对特定任务或行为进行个性化或专门化的聊天机器人进行扩展对话。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "604c8c14",
   "metadata": {},
   "outputs": [],
   "source": [
    "from utils.ready import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cee681b7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},    \n",
    "{'role':'user', 'content':'tell me a joke'},   \n",
    "{'role':'assistant', 'content':'Why did the chicken cross the road'},   \n",
    "{'role':'user', 'content':'I don\\'t know'}  ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "da45ea0f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "To get to the other side, good sir!\n"
     ]
    }
   ],
   "source": [
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ca733f8f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello Isa! How can I assist you today?\n"
     ]
    }
   ],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are friendly chatbot.'},    \n",
    "{'role':'user', 'content':'Hi, my name is Isa'}  ]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ae595bc",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm sorry, but I cannot remind you of your name as I don't have access to that information. Could you please tell me your name? I'd be happy to address you by your name from now on.\n"
     ]
    }
   ],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are friendly chatbot.'},    \n",
    "{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "56cbb817",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your name is Isa.\n"
     ]
    }
   ],
   "source": [
    "messages =  [  \n",
    "{'role':'system', 'content':'You are friendly chatbot.'},\n",
    "{'role':'user', 'content':'Hi, my name is Isa'},\n",
    "{'role':'assistant', 'content': \"Hi Isa! It's nice to meet you. \\\n",
    "Is there anything I can help you with today?\"},\n",
    "{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dedba66a-58b0-40d4-b9ae-47e79ae22328",
   "metadata": {
    "id": "bBg_MpXeYnTq"
   },
   "source": [
    "# OrderBot\n",
    "We can automate the collection of user prompts and assistant responses to build a  OrderBot. The OrderBot will take orders at a pizza restaurant. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e76749ac",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def collect_messages(_):\n",
    "    prompt = inp.value_input\n",
    "    inp.value = ''\n",
    "    context.append({'role':'user', 'content':f\"{prompt}\"})\n",
    "    response = get_completion_from_messages(context) \n",
    "    context.append({'role':'assistant', 'content':f\"{response}\"})\n",
    "    panels.append(\n",
    "        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))\n",
    "    panels.append(\n",
    "        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))\n",
    " \n",
    "    return pn.Column(*panels)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "474b557c",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/javascript": "(function(root) {\n  function now() {\n    return new Date();\n  }\n\n  var force = true;\n\n  if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n    root._bokeh_onload_callbacks = [];\n    root._bokeh_is_loading = undefined;\n  }\n\n  if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n    root._bokeh_timeout = Date.now() + 5000;\n    root._bokeh_failed_load = false;\n  }\n\n  function run_callbacks() {\n    try {\n      root._bokeh_onload_callbacks.forEach(function(callback) {\n        if (callback != null)\n          callback();\n      });\n    } finally {\n      delete root._bokeh_onload_callbacks\n    }\n    console.debug(\"Bokeh: all callbacks have finished\");\n  }\n\n  function load_libs(css_urls, js_urls, js_modules, callback) {\n    if (css_urls == null) css_urls = [];\n    if (js_urls == null) js_urls = [];\n    if (js_modules == null) js_modules = [];\n\n    root._bokeh_onload_callbacks.push(callback);\n    if (root._bokeh_is_loading > 0) {\n      console.debug(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n      return null;\n    }\n    if (js_urls.length === 0 && js_modules.length === 0) {\n      run_callbacks();\n      return null;\n    }\n    console.debug(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n\n    function on_load() {\n      root._bokeh_is_loading--;\n      if (root._bokeh_is_loading === 0) {\n        console.debug(\"Bokeh: all BokehJS libraries/stylesheets loaded\");\n        run_callbacks()\n      }\n    }\n\n    function on_error() {\n      console.error(\"failed to load \" + url);\n    }\n\n    for (var i = 0; i < css_urls.length; i++) {\n      var url = css_urls[i];\n      const element = document.createElement(\"link\");\n      element.onload = on_load;\n      element.onerror = on_error;\n      element.rel = \"stylesheet\";\n      element.type = \"text/css\";\n      element.href = url;\n      console.debug(\"Bokeh: injecting link tag for BokehJS stylesheet: \", url);\n      document.body.appendChild(element);\n    }\n\n    var skip = [];\n    if (window.requirejs) {\n      window.requirejs.config({'packages': {}, 'paths': {'gridstack': 'https://cdn.jsdelivr.net/npm/gridstack@4.2.5/dist/gridstack-h5', 'notyf': 'https://cdn.jsdelivr.net/npm/notyf@3/notyf.min'}, 'shim': {'gridstack': {'exports': 'GridStack'}}});\n      require([\"gridstack\"], function(GridStack) {\n\twindow.GridStack = GridStack\n\ton_load()\n      })\n      require([\"notyf\"], function() {\n\ton_load()\n      })\n      root._bokeh_is_loading = css_urls.length + 2;\n    } else {\n      root._bokeh_is_loading = css_urls.length + js_urls.length + js_modules.length;\n    }    if (((window['GridStack'] !== undefined) && (!(window['GridStack'] instanceof HTMLElement))) || window.requirejs) {\n      var urls = ['https://cdn.holoviz.org/panel/0.14.4/dist/bundled/gridstack/gridstack@4.2.5/dist/gridstack-h5.js'];\n      for (var i = 0; i < urls.length; i++) {\n        skip.push(urls[i])\n      }\n    }    if (((window['Notyf'] !== undefined) && (!(window['Notyf'] instanceof HTMLElement))) || window.requirejs) {\n      var urls = ['https://cdn.holoviz.org/panel/0.14.4/dist/bundled/notificationarea/notyf@3/notyf.min.js'];\n      for (var i = 0; i < urls.length; i++) {\n        skip.push(urls[i])\n      }\n    }    for (var i = 0; i < js_urls.length; i++) {\n      var url = js_urls[i];\n      if (skip.indexOf(url) >= 0) {\n\tif (!window.requirejs) {\n\t  on_load();\n\t}\n\tcontinue;\n      }\n      var element = document.createElement('script');\n      element.onload = on_load;\n      element.onerror = on_error;\n      element.async = false;\n      element.src = url;\n      console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n      document.head.appendChild(element);\n    }\n    for (var i = 0; i < js_modules.length; i++) {\n      var url = js_modules[i];\n      if (skip.indexOf(url) >= 0) {\n\tif (!window.requirejs) {\n\t  on_load();\n\t}\n\tcontinue;\n      }\n      var element = document.createElement('script');\n      element.onload = on_load;\n      element.onerror = on_error;\n      element.async = false;\n      element.src = url;\n      element.type = \"module\";\n      console.debug(\"Bokeh: injecting script tag for BokehJS library: \", url);\n      document.head.appendChild(element);\n    }\n    if (!js_urls.length && !js_modules.length) {\n      on_load()\n    }\n  };\n\n  function inject_raw_css(css) {\n    const element = document.createElement(\"style\");\n    element.appendChild(document.createTextNode(css));\n    document.body.appendChild(element);\n  }\n\n  var js_urls = [\"https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js\", \"https://cdn.bokeh.org/bokeh/release/bokeh-mathjax-2.4.3.min.js\", \"https://unpkg.com/@holoviz/panel@0.14.4/dist/panel.min.js\"];\n  var js_modules = [];\n  var css_urls = [\"https://cdn.holoviz.org/panel/0.14.4/dist/css/alerts.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/card.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/dataframe.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/debugger.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/json.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/loading.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/markdown.css\", \"https://cdn.holoviz.org/panel/0.14.4/dist/css/widgets.css\"];\n  var inline_js = [    function(Bokeh) {\n      inject_raw_css(\"\\n    .bk.pn-loading.arc:before {\\n      background-image: url(\\\"\\\");\\n      background-size: auto calc(min(50%, 400px));\\n    }\\n    \");\n    },    function(Bokeh) {\n      Bokeh.set_log_level(\"info\");\n    },\nfunction(Bokeh) {} // ensure no trailing comma for IE\n  ];\n\n  function run_inline_js() {\n    if ((root.Bokeh !== undefined) || (force === true)) {\n      for (var i = 0; i < inline_js.length; i++) {\n        inline_js[i].call(root, root.Bokeh);\n      }} else if (Date.now() < root._bokeh_timeout) {\n      setTimeout(run_inline_js, 100);\n    } else if (!root._bokeh_failed_load) {\n      console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n      root._bokeh_failed_load = true;\n    }\n  }\n\n  if (root._bokeh_is_loading === 0) {\n    console.debug(\"Bokeh: BokehJS loaded, going straight to plotting\");\n    run_inline_js();\n  } else {\n    load_libs(css_urls, js_urls, js_modules, function() {\n      console.debug(\"Bokeh: BokehJS plotting callback run at\", now());\n      run_inline_js();\n    });\n  }\n}(window));",
      "application/vnd.holoviews_load.v0+json": ""
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/javascript": "\nif ((window.PyViz === undefined) || (window.PyViz instanceof HTMLElement)) {\n  window.PyViz = {comms: {}, comm_status:{}, kernels:{}, receivers: {}, plot_index: []}\n}\n\n\n    function JupyterCommManager() {\n    }\n\n    JupyterCommManager.prototype.register_target = function(plot_id, comm_id, msg_handler) {\n      if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n        var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n        comm_manager.register_target(comm_id, function(comm) {\n          comm.on_msg(msg_handler);\n        });\n      } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n        window.PyViz.kernels[plot_id].registerCommTarget(comm_id, function(comm) {\n          comm.onMsg = msg_handler;\n        });\n      } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n        google.colab.kernel.comms.registerTarget(comm_id, (comm) => {\n          var messages = comm.messages[Symbol.asyncIterator]();\n          function processIteratorResult(result) {\n            var message = result.value;\n            console.log(message)\n            var content = {data: message.data, comm_id};\n            var buffers = []\n            for (var buffer of message.buffers || []) {\n              buffers.push(new DataView(buffer))\n            }\n            var metadata = message.metadata || {};\n            var msg = {content, buffers, metadata}\n            msg_handler(msg);\n            return messages.next().then(processIteratorResult);\n          }\n          return messages.next().then(processIteratorResult);\n        })\n      }\n    }\n\n    JupyterCommManager.prototype.get_client_comm = function(plot_id, comm_id, msg_handler) {\n      if (comm_id in window.PyViz.comms) {\n        return window.PyViz.comms[comm_id];\n      } else if (window.comm_manager || ((window.Jupyter !== undefined) && (Jupyter.notebook.kernel != null))) {\n        var comm_manager = window.comm_manager || Jupyter.notebook.kernel.comm_manager;\n        var comm = comm_manager.new_comm(comm_id, {}, {}, {}, comm_id);\n        if (msg_handler) {\n          comm.on_msg(msg_handler);\n        }\n      } else if ((plot_id in window.PyViz.kernels) && (window.PyViz.kernels[plot_id])) {\n        var comm = window.PyViz.kernels[plot_id].connectToComm(comm_id);\n        comm.open();\n        if (msg_handler) {\n          comm.onMsg = msg_handler;\n        }\n      } else if (typeof google != 'undefined' && google.colab.kernel != null) {\n        var comm_promise = google.colab.kernel.comms.open(comm_id)\n        comm_promise.then((comm) => {\n          window.PyViz.comms[comm_id] = comm;\n          if (msg_handler) {\n            var messages = comm.messages[Symbol.asyncIterator]();\n            function processIteratorResult(result) {\n              var message = result.value;\n              var content = {data: message.data};\n              var metadata = message.metadata || {comm_id};\n              var msg = {content, metadata}\n              msg_handler(msg);\n              return messages.next().then(processIteratorResult);\n            }\n            return messages.next().then(processIteratorResult);\n          }\n        }) \n        var sendClosure = (data, metadata, buffers, disposeOnDone) => {\n          return comm_promise.then((comm) => {\n            comm.send(data, metadata, buffers, disposeOnDone);\n          });\n        };\n        var comm = {\n          send: sendClosure\n        };\n      }\n      window.PyViz.comms[comm_id] = comm;\n      return comm;\n    }\n    window.PyViz.comm_manager = new JupyterCommManager();\n    \n\n\nvar JS_MIME_TYPE = 'application/javascript';\nvar HTML_MIME_TYPE = 'text/html';\nvar EXEC_MIME_TYPE = 'application/vnd.holoviews_exec.v0+json';\nvar CLASS_NAME = 'output';\n\n/**\n * Render data to the DOM node\n */\nfunction render(props, node) {\n  var div = document.createElement(\"div\");\n  var script = document.createElement(\"script\");\n  node.appendChild(div);\n  node.appendChild(script);\n}\n\n/**\n * Handle when a new output is added\n */\nfunction handle_add_output(event, handle) {\n  var output_area = handle.output_area;\n  var output = handle.output;\n  if ((output.data == undefined) || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n    return\n  }\n  var id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n  var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n  if (id !== undefined) {\n    var nchildren = toinsert.length;\n    var html_node = toinsert[nchildren-1].children[0];\n    html_node.innerHTML = output.data[HTML_MIME_TYPE];\n    var scripts = [];\n    var nodelist = html_node.querySelectorAll(\"script\");\n    for (var i in nodelist) {\n      if (nodelist.hasOwnProperty(i)) {\n        scripts.push(nodelist[i])\n      }\n    }\n\n    scripts.forEach( function (oldScript) {\n      var newScript = document.createElement(\"script\");\n      var attrs = [];\n      var nodemap = oldScript.attributes;\n      for (var j in nodemap) {\n        if (nodemap.hasOwnProperty(j)) {\n          attrs.push(nodemap[j])\n        }\n      }\n      attrs.forEach(function(attr) { newScript.setAttribute(attr.name, attr.value) });\n      newScript.appendChild(document.createTextNode(oldScript.innerHTML));\n      oldScript.parentNode.replaceChild(newScript, oldScript);\n    });\n    if (JS_MIME_TYPE in output.data) {\n      toinsert[nchildren-1].children[1].textContent = output.data[JS_MIME_TYPE];\n    }\n    output_area._hv_plot_id = id;\n    if ((window.Bokeh !== undefined) && (id in Bokeh.index)) {\n      window.PyViz.plot_index[id] = Bokeh.index[id];\n    } else {\n      window.PyViz.plot_index[id] = null;\n    }\n  } else if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n    var bk_div = document.createElement(\"div\");\n    bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n    var script_attrs = bk_div.children[0].attributes;\n    for (var i = 0; i < script_attrs.length; i++) {\n      toinsert[toinsert.length - 1].childNodes[1].setAttribute(script_attrs[i].name, script_attrs[i].value);\n    }\n    // store reference to server id on output_area\n    output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n  }\n}\n\n/**\n * Handle when an output is cleared or removed\n */\nfunction handle_clear_output(event, handle) {\n  var id = handle.cell.output_area._hv_plot_id;\n  var server_id = handle.cell.output_area._bokeh_server_id;\n  if (((id === undefined) || !(id in PyViz.plot_index)) && (server_id !== undefined)) { return; }\n  var comm = window.PyViz.comm_manager.get_client_comm(\"hv-extension-comm\", \"hv-extension-comm\", function () {});\n  if (server_id !== null) {\n    comm.send({event_type: 'server_delete', 'id': server_id});\n    return;\n  } else if (comm !== null) {\n    comm.send({event_type: 'delete', 'id': id});\n  }\n  delete PyViz.plot_index[id];\n  if ((window.Bokeh !== undefined) & (id in window.Bokeh.index)) {\n    var doc = window.Bokeh.index[id].model.document\n    doc.clear();\n    const i = window.Bokeh.documents.indexOf(doc);\n    if (i > -1) {\n      window.Bokeh.documents.splice(i, 1);\n    }\n  }\n}\n\n/**\n * Handle kernel restart event\n */\nfunction handle_kernel_cleanup(event, handle) {\n  delete PyViz.comms[\"hv-extension-comm\"];\n  window.PyViz.plot_index = {}\n}\n\n/**\n * Handle update_display_data messages\n */\nfunction handle_update_output(event, handle) {\n  handle_clear_output(event, {cell: {output_area: handle.output_area}})\n  handle_add_output(event, handle)\n}\n\nfunction register_renderer(events, OutputArea) {\n  function append_mime(data, metadata, element) {\n    // create a DOM node to render to\n    var toinsert = this.create_output_subarea(\n    metadata,\n    CLASS_NAME,\n    EXEC_MIME_TYPE\n    );\n    this.keyboard_manager.register_events(toinsert);\n    // Render to node\n    var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n    render(props, toinsert[0]);\n    element.append(toinsert);\n    return toinsert\n  }\n\n  events.on('output_added.OutputArea', handle_add_output);\n  events.on('output_updated.OutputArea', handle_update_output);\n  events.on('clear_output.CodeCell', handle_clear_output);\n  events.on('delete.Cell', handle_clear_output);\n  events.on('kernel_ready.Kernel', handle_kernel_cleanup);\n\n  OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n    safe: true,\n    index: 0\n  });\n}\n\nif (window.Jupyter !== undefined) {\n  try {\n    var events = require('base/js/events');\n    var OutputArea = require('notebook/js/outputarea').OutputArea;\n    if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n      register_renderer(events, OutputArea);\n    }\n  } catch(err) {\n  }\n}\n",
      "application/vnd.holoviews_load.v0+json": ""
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<style>.bk-root, .bk-root .bk:before, .bk-root .bk:after {\n",
       "  font-family: var(--jp-ui-font-size1);\n",
       "  font-size: var(--jp-ui-font-size1);\n",
       "  color: var(--jp-ui-font-color1);\n",
       "}\n",
       "</style>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "ename": "ImportError",
     "evalue": "cannot import name 'warn' from 'bokeh.util.warnings' (d:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\bokeh\\util\\warnings.py)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mImportError\u001b[0m                               Traceback (most recent call last)",
      "File \u001b[1;32md:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\IPython\\core\\formatters.py:974\u001b[0m, in \u001b[0;36mMimeBundleFormatter.__call__\u001b[1;34m(self, obj, include, exclude)\u001b[0m\n\u001b[0;32m    971\u001b[0m     method \u001b[39m=\u001b[39m get_real_method(obj, \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mprint_method)\n\u001b[0;32m    973\u001b[0m     \u001b[39mif\u001b[39;00m method \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m--> 974\u001b[0m         \u001b[39mreturn\u001b[39;00m method(include\u001b[39m=\u001b[39;49minclude, exclude\u001b[39m=\u001b[39;49mexclude)\n\u001b[0;32m    975\u001b[0m     \u001b[39mreturn\u001b[39;00m \u001b[39mNone\u001b[39;00m\n\u001b[0;32m    976\u001b[0m \u001b[39melse\u001b[39;00m:\n",
      "File \u001b[1;32md:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\panel\\viewable.py:623\u001b[0m, in \u001b[0;36mViewable._repr_mimebundle_\u001b[1;34m(self, include, exclude)\u001b[0m\n\u001b[0;32m    620\u001b[0m     loaded \u001b[39m=\u001b[39m hv\u001b[39m.\u001b[39mextension\u001b[39m.\u001b[39m_loaded\n\u001b[0;32m    622\u001b[0m \u001b[39mif\u001b[39;00m config\u001b[39m.\u001b[39mcomms \u001b[39min\u001b[39;00m (\u001b[39m'\u001b[39m\u001b[39mvscode\u001b[39m\u001b[39m'\u001b[39m, \u001b[39m'\u001b[39m\u001b[39mipywidgets\u001b[39m\u001b[39m'\u001b[39m):\n\u001b[1;32m--> 623\u001b[0m     widget \u001b[39m=\u001b[39m ipywidget(\u001b[39mself\u001b[39;49m)\n\u001b[0;32m    624\u001b[0m     \u001b[39mif\u001b[39;00m \u001b[39mhasattr\u001b[39m(widget, \u001b[39m'\u001b[39m\u001b[39m_repr_mimebundle_\u001b[39m\u001b[39m'\u001b[39m):\n\u001b[0;32m    625\u001b[0m         \u001b[39mreturn\u001b[39;00m widget\u001b[39m.\u001b[39m_repr_mimebundle_(include\u001b[39m=\u001b[39minclude, exclude\u001b[39m=\u001b[39mexclude), {}\n",
      "File \u001b[1;32md:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\panel\\io\\notebook.py:384\u001b[0m, in \u001b[0;36mipywidget\u001b[1;34m(obj, **kwargs)\u001b[0m\n\u001b[0;32m    367\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mipywidget\u001b[39m(obj: Any, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs: Any):\n\u001b[0;32m    368\u001b[0m \u001b[39m    \u001b[39m\u001b[39m\"\"\"\u001b[39;00m\n\u001b[0;32m    369\u001b[0m \u001b[39m    Returns an ipywidget model which renders the Panel object.\u001b[39;00m\n\u001b[0;32m    370\u001b[0m \n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    382\u001b[0m \u001b[39m    Returns an ipywidget model which renders the Panel object.\u001b[39;00m\n\u001b[0;32m    383\u001b[0m \u001b[39m    \"\"\"\u001b[39;00m\n\u001b[1;32m--> 384\u001b[0m     \u001b[39mfrom\u001b[39;00m \u001b[39mjupyter_bokeh\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mwidgets\u001b[39;00m \u001b[39mimport\u001b[39;00m BokehModel\n\u001b[0;32m    386\u001b[0m     \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mpane\u001b[39;00m \u001b[39mimport\u001b[39;00m panel\n\u001b[0;32m    387\u001b[0m     model \u001b[39m=\u001b[39m panel(obj, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs)\u001b[39m.\u001b[39mget_root()\n",
      "File \u001b[1;32md:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\jupyter_bokeh\\__init__.py:9\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39m_version\u001b[39;00m \u001b[39mimport\u001b[39;00m __version__\n\u001b[0;32m      7\u001b[0m HERE \u001b[39m=\u001b[39m Path(\u001b[39m__file__\u001b[39m)\u001b[39m.\u001b[39mparent\u001b[39m.\u001b[39mresolve()\n\u001b[1;32m----> 9\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39mwidgets\u001b[39;00m \u001b[39mimport\u001b[39;00m BokehModel\n\u001b[0;32m     10\u001b[0m \u001b[39mwith\u001b[39;00m (HERE \u001b[39m/\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mlabextension\u001b[39m\u001b[39m\"\u001b[39m \u001b[39m/\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mpackage.json\u001b[39m\u001b[39m\"\u001b[39m)\u001b[39m.\u001b[39mopen() \u001b[39mas\u001b[39;00m fid:\n\u001b[0;32m     11\u001b[0m     data \u001b[39m=\u001b[39m json\u001b[39m.\u001b[39mload(fid)\n",
      "File \u001b[1;32md:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\jupyter_bokeh\\widgets.py:33\u001b[0m\n\u001b[0;32m     31\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mbokeh\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mmodels\u001b[39;00m \u001b[39mimport\u001b[39;00m ColumnDataSource, LayoutDOM\n\u001b[0;32m     32\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mbokeh\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mprotocol\u001b[39;00m \u001b[39mimport\u001b[39;00m Protocol\n\u001b[1;32m---> 33\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mbokeh\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mcore\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mserialization\u001b[39;00m \u001b[39mimport\u001b[39;00m Deserializer, Serialized\n\u001b[0;32m     34\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mbokeh\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mmodel\u001b[39;00m \u001b[39mimport\u001b[39;00m Model\n\u001b[0;32m     36\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39m_version\u001b[39;00m \u001b[39mimport\u001b[39;00m __version__\n",
      "File \u001b[1;32md:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\bokeh\\core\\serialization.py:63\u001b[0m\n\u001b[0;32m     47\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mutil\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mdataclasses\u001b[39;00m \u001b[39mimport\u001b[39;00m (\n\u001b[0;32m     48\u001b[0m     Unspecified,\n\u001b[0;32m     49\u001b[0m     dataclass,\n\u001b[0;32m     50\u001b[0m     entries,\n\u001b[0;32m     51\u001b[0m     is_dataclass,\n\u001b[0;32m     52\u001b[0m )\n\u001b[0;32m     53\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mutil\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mserialization\u001b[39;00m \u001b[39mimport\u001b[39;00m (\n\u001b[0;32m     54\u001b[0m     array_encoding_disabled,\n\u001b[0;32m     55\u001b[0m     convert_datetime_type,\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m     61\u001b[0m     transform_series,\n\u001b[0;32m     62\u001b[0m )\n\u001b[1;32m---> 63\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mutil\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mwarnings\u001b[39;00m \u001b[39mimport\u001b[39;00m BokehUserWarning, warn\n\u001b[0;32m     64\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39m.\u001b[39;00m\u001b[39mtypes\u001b[39;00m \u001b[39mimport\u001b[39;00m ID\n\u001b[0;32m     66\u001b[0m \u001b[39mif\u001b[39;00m TYPE_CHECKING:\n",
      "\u001b[1;31mImportError\u001b[0m: cannot import name 'warn' from 'bokeh.util.warnings' (d:\\Appdata\\miniconda3\\envs\\openai\\lib\\site-packages\\bokeh\\util\\warnings.py)"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Column\n",
       "    [0] TextInput(placeholder='Enter text here…')\n",
       "    [1] Row\n",
       "        [0] Button(name='Chat!')\n",
       "    [2] ParamFunction(function, _pane=Column, height=300, loading_indicator=True)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import panel as pn  # GUI\n",
    "pn.extension()\n",
    "\n",
    "panels = [] # collect display \n",
    "\n",
    "context = [ {'role':'system', 'content':\"\"\"\n",
    "You are OrderBot, an automated service to collect orders for a pizza restaurant. \\\n",
    "You first greet the customer, then collects the order, \\\n",
    "and then asks if it's a pickup or delivery. \\\n",
    "You wait to collect the entire order, then summarize it and check for a final \\\n",
    "time if the customer wants to add anything else. \\\n",
    "If it's a delivery, you ask for an address. \\\n",
    "Finally you collect the payment.\\\n",
    "Make sure to clarify all options, extras and sizes to uniquely \\\n",
    "identify the item from the menu.\\\n",
    "You respond in a short, very conversational friendly style. \\\n",
    "The menu includes \\\n",
    "pepperoni pizza  12.95, 10.00, 7.00 \\\n",
    "cheese pizza   10.95, 9.25, 6.50 \\\n",
    "eggplant pizza   11.95, 9.75, 6.75 \\\n",
    "fries 4.50, 3.50 \\\n",
    "greek salad 7.25 \\\n",
    "Toppings: \\\n",
    "extra cheese 2.00, \\\n",
    "mushrooms 1.50 \\\n",
    "sausage 3.00 \\\n",
    "canadian bacon 3.50 \\\n",
    "AI sauce 1.50 \\\n",
    "peppers 1.00 \\\n",
    "Drinks: \\\n",
    "coke 3.00, 2.00, 1.00 \\\n",
    "sprite 3.00, 2.00, 1.00 \\\n",
    "bottled water 5.00 \\\n",
    "\"\"\"} ]  # accumulate messages\n",
    "\n",
    "\n",
    "inp = pn.widgets.TextInput(value=\"Hi\", placeholder='Enter text here…')\n",
    "button_conversation = pn.widgets.Button(name=\"Chat!\")\n",
    "\n",
    "interactive_conversation = pn.bind(collect_messages, button_conversation)\n",
    "\n",
    "dashboard = pn.Column(\n",
    "    inp,\n",
    "    pn.Row(button_conversation),\n",
    "    pn.panel(interactive_conversation, loading_indicator=True, height=300),\n",
    ")\n",
    "\n",
    "dashboard"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a0ee11b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sure, here's a JSON summary of the order:\n",
      "\n",
      "```\n",
      "{\n",
      "  \"pizza\": [\n",
      "    {\n",
      "      \"type\": \"pepperoni\",\n",
      "      \"size\": \"large\",\n",
      "      \"price\": 12.95\n",
      "    },\n",
      "    {\n",
      "      \"type\": \"cheese\",\n",
      "      \"size\": \"medium\",\n",
      "      \"price\": 9.25\n",
      "    }\n",
      "  ],\n",
      "  \"toppings\": [\n",
      "    {\n",
      "      \"type\": \"extra cheese\",\n",
      "      \"price\": 2.00\n",
      "    },\n",
      "    {\n",
      "      \"type\": \"mushrooms\",\n",
      "      \"price\": 1.50\n",
      "    }\n",
      "  ],\n",
      "  \"drinks\": [\n",
      "    {\n",
      "      \"type\": \"coke\",\n",
      "      \"size\": \"large\",\n",
      "      \"price\": 3.00\n",
      "    },\n",
      "    {\n",
      "      \"type\": \"sprite\",\n",
      "      \"size\": \"small\",\n",
      "      \"price\": 2.00\n",
      "    }\n",
      "  ],\n",
      "  \"sides\": [\n",
      "    {\n",
      "      \"type\": \"fries\",\n",
      "      \"size\": \"large\",\n",
      "      \"price\": 4.50\n",
      "    }\n",
      "  ],\n",
      "  \"total_price\": 35.20\n",
      "}\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "messages =  context.copy()\n",
    "messages.append(\n",
    "{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\\\n",
    " The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},    \n",
    ")\n",
    " #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},    \n",
    "\n",
    "response = get_completion_from_messages(messages, temperature=0)\n",
    "print(response)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "3153c581-1c72-497a-9293-8db3bcb804fc",
   "metadata": {},
   "source": [
    "您可以修改菜单或说明来创建自己的订单机器人！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cc84122",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
